import { forkCall } from '@/utils';
import { useRef } from 'react';
import { useCall, useMountedRef } from '.';

function useCreateCall() {
  let index = 0;
  const next = () => index++;
  const mountedRef = useMountedRef();
  const callRef = useRef({});
  const argsRef = useRef({});

  const of = useCall((keyOfList, fn, ...args) => {
    const current = keyOfList ?? next();
    argsRef.current[current] = [fn, ...args];
    if (!callRef.current[current]) {
      callRef.current[current] = (...nextArgs) => {
        const [refFn, ...refArgs] = argsRef.current[current];
        return forkCall(mountedRef, refFn, ...refArgs, ...nextArgs);
      };
    }

    return callRef.current[current];
  });

  const call = useCall((fn, ...args) => of(next(), fn, ...args));

  call.of = of;

  return call;
}

export default useCreateCall;
